/*
	   _           _      _           _     _ 
	  (_)         | |    | |         (_)   | |
	   _ _   _ ___| |_ __| |_ __ ___  _  __| |
	  | | | | / __| __/ _` | '__/ _ \| |/ _` |
	  | | |_| \__ \ || (_| | | | (_) | | (_| |
	  | |\__,_|___/\__\__,_|_|  \___/|_|\__,_|
	 _/ |                                     
	|__/ 
	
	Copyright 2013 Caspar Isemer and and Eva Krueger, http://justdroid.org
	
	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at
	
		http://www.apache.org/licenses/LICENSE-2.0
	
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License. 
*/

package org.justdroid.justdroid;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class SettingsFont extends JustDroidActivity {

	/** Declare variables and UI elements **/
	private Spinner spinnerFontType;
	private SpinnerAdapter adapter;
	private TextView txtPreview, txtFontSize, txtFontType;
	private Button btnIncrease, btnDecrease, btnReset;
	private TextView txtNumber;
	private SharedPreferences preferences;
	private Editor editor;
	
	void attachKeyListener(final Button button, final int buttonFlag) {
		button.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
				if(keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
					switch(keyCode) {
					case KeyEvent.KEYCODE_DPAD_CENTER:
					case KeyEvent.KEYCODE_ENTER:
						switch(buttonFlag) {
						case 1:
							reset();
							break;
						case 2:
							increase();
							break;
						case 3:
							decrease();
							break;
						}
						break;
					}
				}
				return false;
			}
		});
	}
	
	/** Function to attach onTouchListener and onFocusListener to the buttons **/
	void attachListenerToButton(Button button) {
		final String text = button.getText().toString();
		/*button.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View view, MotionEvent arg1) {
				giveFeedback(text);
				return false;
			}
		});*/
		button.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View view, boolean arg1) {
				giveFeedback(text);
			}
		});
	}
	
	/** Function to attach onTouchListener and onFocusListener to the text views **/
	void attachListenerToTextView(TextView textView) {
		/*textView.setOnTouchListener(new OnTouchListener() {	
			@Override
			public boolean onTouch(View view, MotionEvent arg1) {
				giveFeedback(((TextView)view).getText().toString());
				return false;
			}
		});*/
		
		textView.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View view, boolean hasFocus) {
				if(hasFocus) {
					giveFeedback(((TextView)view).getText().toString());
				}
			}
		});
	}
	
	/** Function to attach onTouchListener to the spinners **/
	/*void attachListenerToSpinner(Spinner spinner) {
		spinner.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View view, MotionEvent arg1) {
				//vibrate
				Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			    vibrator.vibrate(500);
				return false;
			}
		});
	}*/
	
	/** Function to attach onItemSelectedListener to the spinners **/
	void attachListenerToSpinnerItem(final Spinner spinner) {
		
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			@SuppressLint("DefaultLocale")
			@Override
			public void onItemSelected(AdapterView<?> arg0, View view, int position,
					long arg3) {
					String typeface = Integer.toString(position);
					//save in SharedPreferences
					preferences = getSharedPreferences(getResources().getString(R.string.fonttype), 0);
					if(typeface.equals(getResources().getString(R.string.none))) {
						txtPreview.setTypeface(Typeface.create("default", Typeface.NORMAL));
					}
					else if(typeface.equals(getResources().getString(R.string.serif))) {
						txtPreview.setTypeface(Typeface.SERIF);
					}
					else if(typeface.equals(getResources().getString(R.string.monospace))) {
						txtPreview.setTypeface(Typeface.MONOSPACE);
					}
					editor = preferences.edit();
					editor.putInt("typeface", position);
					if(editor.commit()) {
						if(Utils.isAccessibilityEnabled(getApplicationContext()))
							TTS.speak(spinner.getSelectedItem().toString() + " " + getResources().getString(R.string.appliedTypeSuccess));
						Toast.makeText(getApplicationContext(), spinner.getSelectedItem().toString() + " " + getResources().getString(R.string.appliedTypeSuccess), Toast.LENGTH_SHORT).show();
					}
					else {
						if(Utils.isAccessibilityEnabled(getApplicationContext()))
							TTS.speak(spinner.getSelectedItem().toString() + " " + getResources().getString(R.string.appliedTypeFailure));
						Toast.makeText(getApplicationContext(), spinner.getSelectedItem().toString() + " " + getResources().getString(R.string.appliedTypeFailure), Toast.LENGTH_SHORT).show();
					}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {				
			}
		});
	}
	
	void decrease() {
		int number = Integer.valueOf(txtNumber.getText().toString());
		if(number - 1 >= Integer.valueOf(getResources().getString(R.string.lowerLimit))) {
			txtNumber.setText(Integer.toString(number - 1));
			txtPreview.setTextSize(Float.valueOf(txtNumber.getText().toString()));
			//save in SharedPreferences
			preferences = getSharedPreferences(getResources().getString(R.string.size), 0);
			editor = preferences.edit();
			editor.putFloat("size", Float.valueOf(txtNumber.getText().toString()));
			if(editor.commit()) {
				if(Utils.isAccessibilityEnabled(getApplicationContext()))
					TTS.speak(txtNumber.getText().toString() + " " + getResources().getString(R.string.appliedFontSizeSuccess));
				Toast.makeText(getApplicationContext(), txtNumber.getText().toString() + " " + getResources().getString(R.string.appliedFontSizeSuccess), Toast.LENGTH_SHORT).show();
			}
			else {
				if(Utils.isAccessibilityEnabled(getApplicationContext()))
					TTS.speak(txtNumber.getText().toString() + " " + getResources().getString(R.string.appliedFontSizeFailure));
				Toast.makeText(getApplicationContext(), txtNumber.getText().toString() + " " + getResources().getString(R.string.appliedFontSizeFailure), Toast.LENGTH_SHORT).show();
			}
		}
		else {
			if(Utils.isAccessibilityEnabled(getApplicationContext()))
				TTS.speak(getResources().getString(R.string.reachedLowerLimit));
			Toast.makeText(getApplicationContext(), getResources().getString(R.string.reachedLowerLimit), Toast.LENGTH_SHORT).show();
		}
	}
	
	void increase() {
		int number = Integer.valueOf(txtNumber.getText().toString());
		if(number + 1 <= Integer.valueOf(getResources().getString(R.string.maxLimit))) {
			txtNumber.setText(Integer.toString(number + 1));
			txtPreview.setTextSize(Float.valueOf(txtNumber.getText().toString()));
			//save in SharedPreferences
			preferences = getSharedPreferences(getResources().getString(R.string.size), 0);
			editor = preferences.edit();
			editor.putFloat("size", Float.valueOf(txtNumber.getText().toString()));
			if(editor.commit()) {
				if(Utils.isAccessibilityEnabled(getApplicationContext()))
					TTS.speak(txtNumber.getText().toString() + " " + getResources().getString(R.string.appliedFontSizeSuccess));
				Toast.makeText(getApplicationContext(), txtNumber.getText().toString() + " " + getResources().getString(R.string.appliedFontSizeSuccess), Toast.LENGTH_SHORT).show();
			}
			else {
				if(Utils.isAccessibilityEnabled(getApplicationContext()))
					TTS.speak(txtNumber.getText().toString() + " " + getResources().getString(R.string.appliedFontSizeFailure));
				Toast.makeText(getApplicationContext(), txtNumber.getText().toString() + " " + getResources().getString(R.string.appliedFontSizeFailure), Toast.LENGTH_SHORT).show();
			}
		}
		else {
			if(Utils.isAccessibilityEnabled(getApplicationContext()))
				TTS.speak(getResources().getString(R.string.reachedMaxLimit));
			Toast.makeText(getApplicationContext(), getResources().getString(R.string.reachedMaxLimit), Toast.LENGTH_SHORT).show();
		}
	}
	
	void reset() {
		SettingsFont.this.preferences = getSharedPreferences(getResources().getString(R.string.fonttype), 0);
		editor = SettingsFont.this.preferences.edit();
		editor.clear();
		editor.commit();
		SettingsFont.this.preferences = getSharedPreferences(getResources().getString(R.string.size), 0);
		editor = SettingsFont.this.preferences.edit();
		editor.clear();
		editor.commit();
		if(Utils.isAccessibilityEnabled(getApplicationContext()))
			TTS.speak(getResources().getString(R.string.resetFontSuccess));
		Toast.makeText(getApplicationContext(), getResources().getString(R.string.resetFontSuccess), Toast.LENGTH_SHORT).show();
	}
	
	/** Function to announce the text of the view that received focus or on which the onTouch event was triggered**/
	void giveFeedback(String text) {
		if(text.trim().equals(getResources().getString(R.string.minus)))
			text = getResources().getString(R.string.minusDescription);
		//vibrate
		Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	    vibrator.vibrate(300);
	    //TTS feedback
	    if(!TTS.isSpeaking())
	    	TTS.speak(text);
	}
	
	/** Create the Contact Details menu activity **/
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.settingsfont);
		super.onCreate(savedInstanceState);
		
		/** get UI elements **/
		txtPreview = (TextView) findViewById(R.id.txtPreview);
		txtFontSize = (TextView) findViewById(R.id.txtFontSize);
		txtFontType = (TextView) findViewById(R.id.txtFontType);
		btnIncrease = (Button) findViewById(R.id.btnIncrease);
		btnDecrease = (Button) findViewById(R.id.btnDecrease);
		btnReset = (Button) findViewById(R.id.btnApplyFont);
		txtNumber = (TextView) findViewById(R.id.txtNumber);
		spinnerFontType = (Spinner) findViewById(R.id.fontType);
		adapter = new SpinnerAdapter(getApplicationContext(), Utils.fontType);
		spinnerFontType.setAdapter(adapter);
		
		attachListenerToTextView(txtFontSize);
		attachListenerToTextView(txtFontType);
		
		attachListenerToButton(btnIncrease);
		attachListenerToButton(btnDecrease);
		attachListenerToButton(btnReset);
		
		//attachListenerToSpinner(spinnerFontType);
		attachListenerToSpinnerItem(spinnerFontType);
		
		attachKeyListener(btnReset, 1);
		attachKeyListener(btnIncrease, 2);
		attachKeyListener(btnDecrease, 3);
		
		btnReset.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				reset();
			}
		});
		
		btnIncrease.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				increase();
			}
		});
		
		btnDecrease.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				decrease();
			}
		});
		
		/** Put most everything before here **/
	}
	
	@Override
	public void onResume() {
		super.onResume();
		
		txtNumber.setText(Float.toString(getSharedPreferences(getResources().getString(R.string.size), 0).getFloat("size", Float.valueOf(getResources().getString(R.string.defaultFontSize)))));
		spinnerFontType.setSelection(getSharedPreferences(getResources().getString(R.string.fonttype), 0).getInt("typeface", 0));
		//get the root layout
		LinearLayout layout = (LinearLayout) findViewById(R.id.settingsfont);
		Utils.applyFontColorChanges(getApplicationContext(), layout);
		Utils.applyFontSizeChanges(getApplicationContext(), layout);  
		Utils.applyFontTypeChanges(getApplicationContext(), layout);
	}
}
